/*
 * UsersManagerBean.java
 *
 * Created on 12 wrzesie� 2007, 22:07
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package info.mikrotubula.managers;

import info.mikrotubula.db.Users;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Krystian
 */
@Stateless
public class UsersManagerBean implements UsersManagerLocal {
    
    @PersistenceContext(unitName = "persistence")
    protected EntityManager em;
    //@Resource
    //UserTransaction tx;
    
    /** Creates a new instance of UsersManagerBean */
    public UsersManagerBean() {
    }
    
    public Users createUser(Users user) {
        try {
            em.persist(user);
        } catch (Exception ex) {
            ex.printStackTrace();
        } 
        return user;
    }

    @SuppressWarnings("unchecked")
    public List<Users> getUsers() {
        return (List<Users>) em.createNamedQuery("Users.findAll").getResultList();
    }  
    
    public Users findById(Integer usrId) {
        try {
        Users user = (Users) em.createNamedQuery("Users.findByUsrId")
            .setParameter("usrId", usrId)
            .getSingleResult();
        return user;
        } catch (NoResultException e) {
            return null;
        }
            
    }
    
    public Users findByNameAndPass(String userName, String userPass) {
        try {
            Users user = (Users) em.createNamedQuery("Users.findByNameAndPass")
                .setParameter("usrName", userName)
                .setParameter("usrPass", userPass)
                .getSingleResult();
            return user;
        } catch (NoResultException e) {
            return null;
        }
    }
    
    public Boolean delete(Users user) {
        try {
            em.remove(em.merge(user));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public Boolean edit(Users user) {
        try {
            Users userx = em.find(Users.class, user.getUsrId());
            userx.setUsrName(user.getUsrName());
            userx.setUsrFirstName(user.getUsrFirstName());
            userx.setUsrLastName(user.getUsrLastName());
            if (user.getUsrPass() != null) userx.setUsrPass(user.getUsrPass());
            em.merge(userx);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public List<Users> search(String searchString) {
        return (List<Users>) em.createNamedQuery("Users.search").setParameter("searchString", "%" + searchString + "%").getResultList();
    }
 }
